package com.gongpingjialoan.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.BuyCarVipActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AppData;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.VIPEb;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.AppUtils;
import com.gongpingjialoan.utility.PayUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.widget.LoadingDialog;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {


    private static final int ALI_PAY_FLAG = 1;
    private static final int WEIXIN_PAY_FLAG = 2;
    public static final String aliAppId = "2016111002684219";
    private IWXAPI api;
    private NetDataJson mWeixinPayJson;
    private NetDataJson mAlipayPayJson;
    private int mPayType = 0;
    private ImageView aliImg;
    private ImageView weixinImg;
    private String car_id;
    private String view_date;
    private LoadingDialog mLoadingDialog;
    private String mType;
    private int mPrice;

    private String action_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Const.WX_APP_KEY);
        api.handleIntent(getIntent(), this);
        setTitle("支付");
        initView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        action_type = b.getString("action_type");
        car_id = b.getString("car_id", "0");
        view_date = b.getString("view_date", "0");
        mPrice = b.getInt("price");
        mType = b.getString("type");
        if (!TextUtils.isEmpty(action_type)) {
            AppData data = GPJApplication.getInstance().mAppData;
            if (data != null) {
                ((TextView) findViewById(R.id.money)).setText("¥" + (int)(data.getData().getVip_charge_price().getValue() / 100f));
            }
            ((TextView) findViewById(R.id.price_des)).setText("开通会员");


        } else {
            ((TextView) findViewById(R.id.money)).setText((String.valueOf(mPrice / 100.0)));
        }


    }

    @Override
    protected void onDestroy() {
        if (mWeixinPayJson != null) {
            mWeixinPayJson.cancelTask();
        }
        if (mAlipayPayJson != null) {
            mAlipayPayJson.cancelTask();
        }
        super.onDestroy();
    }

    public void initView() {
        setTitle("支付");
        aliImg = (ImageView) findViewById(R.id.alipay_img);
        weixinImg = (ImageView) findViewById(R.id.weixin_img);
        findViewById(R.id.pay_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPayType == 0) {
                    Toast.makeText(WXPayEntryActivity.this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                } else if (mPayType == ALI_PAY_FLAG) {
                    if (AppUtils.isAvilible(WXPayEntryActivity.this, "com.eg.android.AlipayGphone")) {
                        if (TextUtils.isEmpty(action_type)) {
                            zhifubao();
                        } else {
                            vip_pay("ali");
                        }

                    } else {
                        Toast.makeText(WXPayEntryActivity.this, "请安装支付宝", Toast.LENGTH_SHORT).show();
                    }
                } else if (mPayType == WEIXIN_PAY_FLAG) {
                    if (isWXAppInstalledAndSupported()) {
                        if (TextUtils.isEmpty(action_type)) {
                            payweixin();
                        } else {
                            vip_pay("wechat");
                        }

                    } else {
                        Toast.makeText(WXPayEntryActivity.this, "请安装微信", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        findViewById(R.id.zhifubao).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "payAli", System.currentTimeMillis(), 1f));
                mPayType = ALI_PAY_FLAG;
                aliImg.setSelected(true);
                weixinImg.setSelected(false);
            }
        });

        findViewById(R.id.weixin).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                StepMonitor.getInstance().addMonitor(new Monitor("click", "payWechat", System.currentTimeMillis(), 1f));
                mPayType = WEIXIN_PAY_FLAG;
                aliImg.setSelected(false);
                weixinImg.setSelected(true);
            }
        });
        mLoadingDialog = new LoadingDialog(this);
    }

    private void payweixin() {

        mWeixinPayJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject j) {
                mLoadingDialog.dismiss();
                try {
                    JSONObject j1 = j.getJSONObject("data");
                    JSONObject j2 = j1.getJSONObject("pay_info");
                    JSONObject json = j2.getJSONObject("weixin_msg");
                    PayReq req = new PayReq();
                    req.appId = Const.WX_APP_KEY;
                    req.partnerId = json.getString("partnerid");
                    req.prepayId = json.getString("prepay_id");
                    req.nonceStr = j2.getString("nonce_str");
                    req.timeStamp = json.getString("timestamp");
                    req.packageValue = json.getString("package");
                    req.sign = json.getString("sign");
//                    req.extData			= "app data"; // optional
                    api.sendReq(req);
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDataJsonError(String errorMessage) {
                showTips(4, errorMessage);
                mLoadingDialog.dismiss();
            }

        });
        mLoadingDialog.show();


        if ("car_ordered_record".equals(mType)) {
            mWeixinPayJson.addParam("car_id", car_id);
            mWeixinPayJson.setUrl(API.order_car_pay);
        } else {
            mWeixinPayJson.addParam("promo_car_id", car_id);
            mWeixinPayJson.setUrl(API.order_promo_car_pay);
        }

        mWeixinPayJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mWeixinPayJson.addParam("order_fee", mPrice + "");
        mWeixinPayJson.addParam("platform", "wechat");
        mWeixinPayJson.addParam("view_date", view_date);
        mWeixinPayJson.request("post");


    }

    private void zhifubao() {

        mAlipayPayJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject j) {
                mLoadingDialog.dismiss();
                try {
                    JSONObject j1 = j.getJSONObject("data");
                    JSONObject json = j1.getJSONObject("pay_info");

                    PayUtil pay = new PayUtil(json, WXPayEntryActivity.this, 1);
                    pay.pay();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDataJsonError(String errorMessage) {
                mLoadingDialog.dismiss();
                showTips(4, errorMessage);
            }

        });
        mLoadingDialog.show();
        if ("car_ordered_record".equals(mType)) {
            mAlipayPayJson.addParam("car_id", car_id);
            mAlipayPayJson.setUrl(API.order_car_pay);
        } else {
            mAlipayPayJson.addParam("promo_car_id", car_id);
            mAlipayPayJson.setUrl(API.order_promo_car_pay);
        }
        mAlipayPayJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mAlipayPayJson.addParam("order_fee", mPrice + "");
        mAlipayPayJson.addParam("platform", "ali");
        mAlipayPayJson.addParam("view_date", view_date);
        mAlipayPayJson.request("post");

    }


    private void vip_pay(final String platform) {
        mAlipayPayJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject j) {
                mLoadingDialog.dismiss();
                try {
                    JSONObject j1 = j.getJSONObject("data");
                    JSONObject json = j1.getJSONObject("pay_info");

                    if ("ali".equals(platform)) {
                        PayUtil pay = new PayUtil(json, WXPayEntryActivity.this, 0);
                        pay.pay();
                    } else {
                        try {

                            JSONObject wxjson = json.getJSONObject("weixin_msg");
                            PayReq req = new PayReq();
                            req.appId = Const.WX_APP_KEY;
                            req.partnerId = wxjson.getString("partnerid");
                            req.prepayId = wxjson.getString("prepay_id");
                            req.nonceStr = json.getString("nonce_str");
                            req.timeStamp = wxjson.getString("timestamp");
                            req.packageValue = wxjson.getString("package");
                            req.sign = wxjson.getString("sign");
//                    req.extData			= "app data"; // optional
                            api.sendReq(req);
                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDataJsonError(String errorMessage) {
                mLoadingDialog.dismiss();
                showTips(4, errorMessage);
            }

        });
        mLoadingDialog.show();
        mAlipayPayJson.setUrl(API.vip_pay);
        mAlipayPayJson.addParam("platform", platform);

        mAlipayPayJson.request("post");
    }

    private boolean isWXAppInstalledAndSupported() {

        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }


    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == 0) {
                showTips(1, "支付成功!");
                if (TextUtils.isEmpty(action_type)) {
                    Intent intent = new Intent(WXPayEntryActivity.this, MainActivity.class);
                    intent.putExtra("type", "pay");
                    startActivity(intent);
                } else {
                    UserManager mUserManager = new UserManager(WXPayEntryActivity.this);
                    mUserManager = mUserManager.LoadUserInfo();
                    mUserManager.setIs_vip(true);
                    mUserManager.SaveUserInfo(mUserManager);
                    EventBus.getDefault().post(new VIPEb());
                    if(!mUserManager.isBuy_car_recommend_flag()){
                        Intent it = new Intent(WXPayEntryActivity.this, BuyCarVipActivity.class);
                        startActivity(it);
                    }

                }

            } else if (resp.errCode == -2) {
                showTips(1, "支付已取消!");
                finish();
            } else {
                showTips(1, "支付失败!" + resp.errCode);
                finish();
            }

        }
    }
}
